import { asyncRoutes, commonRoutes } from '@/router'

/**
 * @param {Array} roles
 * @param {Object} route
 */
function hasPermission(roles, route) {
  if (roles.includes(route.name)) {
    return true
  } else if (route.children && route.children.length === 1) {
    // 兼容路由权限树形图，防止没有父级name时造成权限递归未能正确获取路由
    return roles.includes(route.children[0].name)
  } else {
    return false
  }
}

/**
 * 根据权限过滤异步路由
 * @param {Array} routes 异步路由集合
 * @param {Array} roles 包含Route.name的集合
 */
function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  return res
}

const state = {
  routes: [],
  addAsyncRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addAsyncRoutes = routes
    state.routes = commonRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
